function visgrabShowResults(ResultDataFiles, MethodLabels, outputType)
% function visgrabShowResults(ResultDataFiles, MethodLabels, outputType)
%
% This Matlab script, located in the folder matlab, can be used to display the
% results in the data file. The script can output the distribution of grasp
% results either as a stacked-bar plot or as TeX/HTML tables. The grasp 
% measurements and grasp success per object can be outputted as TeX/HTML tables.
% Multiple result data files can be given as arguments to the script so that 
% the results of different methods can be easily compared.
% 
% Usage: visgrabShowResults(ResultDataFiles, MethodLabels, outputType)
%   ResultDataFiles  A cell array containing the file locators of all results
%                    data files that need to be displayed.
%   MethodLabels	 A cell array containing strings with the name of each
%   		         grasp-generation method.
%   outputType	     A string that is either 'plot', 'tex', or 'html'.
% Write tex or html files with the table showing the grasp results

if(nargin < 3 || ( ~strcmp(outputType, 'tex') && ~strcmp(outputType, 'html') && ~strcmp(outputType, 'plot') ) )
    disp('Give the condition as first parameter [textured | non-textured]');
    return
end

global plotWidth
global plotHeight;
plotWidth = 560; %900
plotHeight = 200;

%% The result types returned by RobWork
%The code for the different grasp results. 
resUnInitialized = 0;
resSuccess = 1;
resCollisionInitially = 2;
resObjectMissed = 3;
resObjectDropped = 4;
resObjectSlipped = 5;
resTimeOut = 6;
resSimulationFailure = 7;
resCollisionFiltered = 8;


%% The object names for single and double objects scenes in VisGraB
% The names of the single objects
singleObject{1} = 'amicelli';
singleObject{2} = 'breadbox';
singleObject{3} = 'burti';
singleObject{4} = 'cleaningbottle';
singleObject{5} = 'cocacola';
singleObject{6} = 'corny';
singleObject{7} = 'denkmit';
singleObject{8} = 'greencup';
singleObject{9} = 'icecoffee';
singleObject{10} = 'marmelade';
singleObject{11} = 'peachcan';
singleObject{12} = 'pure';
singleObject{13} = 'saltbox';
singleObject{14} = 'saltcylinder';
singleObject{15} = 'sucker';
singleObject{16} = 'tomato';
singleObject{17} = 'waterjug';
singleObject{18} = 'whitecup';

% The names of the objects in the double-object scenes
doubleObject{1} = 'ami-whi';
doubleObject{2} = 'bre-pea';
doubleObject{3} = 'bur-den';
doubleObject{4} = 'cle-suc';
doubleObject{5} = 'coc-scy';
doubleObject{6} = 'cor-gre';
doubleObject{7} = 'ice-sbo';
doubleObject{8} = 'mar-pur';
doubleObject{9} = 'tom-wat';

% The IDs of the objects in the double-object scenes
doubleObjectCombination{1} = '1-18';
doubleObjectCombination{2} = '2-11';
doubleObjectCombination{3} = '3-7';
doubleObjectCombination{4} = '4-15';
doubleObjectCombination{5} = '5-14';
doubleObjectCombination{6} = '6-8';
doubleObjectCombination{7} = '9-13';
doubleObjectCombination{8} = '10-12';
doubleObjectCombination{9} = '16-17';

SceneSetsSD{1} = 0:(length(singleObject)-1); % In data file, IDs start running from zero
SceneSetsSD{2} = 0:(length(doubleObject)-1);


%% Labels as shown in the tables / plots
% The labels of the different grasp results as displayed in the tables
resultType{1} = 'stable   ';
resultType{2} = 'slipped  ';
resultType{3} = 'dropped  ';
resultType{4} = 'missed   ';
resultType{5} = 'collision';
resultType{6} = 'nograsp';
% The description of the different conditions for single and double-object
%  scenes as used in the tables/plots
sceneSectionDescription{1}{1} = 'standing';
sceneSectionDescription{1}{2} = 'laying  ';
sceneSectionDescription{1}{3} = 'all     ';
sceneSectionDescription{2}{1} = 'apart   ';
sceneSectionDescription{2}{2} = 'close   ';
sceneSectionDescription{2}{3} = 'all     ';


%% Open all results data files
for fileI = 1:length(ResultDataFiles)
    % Read the result data
    resultDataFile = ResultDataFiles{fileI};
    [headerStr, dataT] = hdrload(resultDataFile);
    header = strread(headerStr, '%s');
    h{fileI}.header = header;
    h{fileI}.textureConditionID = find(strcmp( header, 'textureConditionID' ));
    h{fileI}.nrObjects = find(strcmp( header, 'nrObjects' ));
    h{fileI}.sceneSetID = find(strcmp( header, 'sceneSetID' ));
    h{fileI}.poseID = find(strcmp( header, 'poseID' ));
    h{fileI}.graspID = find(strcmp( header, 'graspID' ));
    h{fileI}.graspResult = find(strcmp( header, 'graspResult' ));
    h{fileI}.graspGWSQuality = find(strcmp( header, 'graspGWSQuality' ));
    h{fileI}.liftGWSQuality = find(strcmp( header, 'liftGWSQuality' ));
    h{fileI}.liftQuality = find(strcmp( header, 'liftQuality' ));

    perCollisionFiltered = size( dataT(dataT(:,h{fileI}.graspResult)==resCollisionFiltered, :), 1) / size(dataT, 1);
    fprintf('Percentage of grasps filtered out based on collision prediction: %2.1f%%\n', 100*perCollisionFiltered);
    dataT = dataT(dataT(:,h{fileI}.graspResult)~=resCollisionFiltered, :);
    dataTotalArray{fileI} = dataT;
end

TextureConditions = {'textured', 'non-textured'};

for condI=1:length(TextureConditions)
    textureCondition = TextureConditions{condI};
    textureConditionID = condI-1; % In data file, IDs start running from zero
    
    %Write to tex file, make header
    if(strcmp(outputType, 'tex'))
        fdResDist = fopen(sprintf('results_distribution_%s.tex', textureCondition), 'w+');
        fdResMeas = fopen(sprintf('results_measures_%s.tex', textureCondition), 'w+');
    elseif(strcmp(outputType, 'html'))
        fdResDist = fopen(sprintf('results_distribution_%s.html', textureCondition), 'w+');
        fdResMeas = fopen(sprintf('results_measures_%s.html', textureCondition), 'w+');
    end        
    
    if(strcmp(outputType, 'tex'))
        writeTEXBeginAllObjectTableDist(fdResDist, textureCondition);
        writeTEXBeginAllObjectTableMeas(fdResMeas, textureCondition);
    elseif(strcmp(outputType, 'html'))
        writeHTMLBeginAllObjectTableDist(fdResDist, textureCondition);
        writeHTMLBeginAllObjectTableMeas(fdResMeas, textureCondition);
    end
    
    ResultsPerObject = {};


    % Loop over single and double object scenes
    for singleDoubleI=1:2    % Create a table with results for single and for double-object scenes
        
        if(singleDoubleI==1)
            complexity = 'single';
        else
            complexity = 'double';
        end
        
        SceneSets = SceneSetsSD{singleDoubleI};

        
        %%
        % Create table headers
        if(strcmp(outputType, 'tex'))
            writeTEXHeaderAllObjectDist(fdResDist, singleDoubleI, MethodLabels);
            writeTEXHeaderAllObjectMeas(fdResMeas, singleDoubleI, MethodLabels);
        elseif(strcmp(outputType, 'html'))
            writeHTMLHeaderAllObjectDist(fdResDist, singleDoubleI, MethodLabels);
            writeHTMLHeaderAllObjectMeas(fdResMeas, singleDoubleI, MethodLabels);
        else
            createPlot()
        end
        %%
        
        %%
        % Process the data for the different conditions: standing/lying/all,
        % far/close/all
        for sceneSectionI=1:3
            if(sceneSectionI==1)
                Poses = 0:3;        % In data file, IDs start running from zero
            elseif(sceneSectionI==2)
                Poses = 4:7;
            else
                Poses = 0:7;
            end
            
            Results = {};
            for fileI = 1:length(ResultDataFiles)
                dataTotal = dataTotalArray{fileI};
                Results{fileI} = [];
                
                for ssI = 1:length(SceneSets)
                    ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{fileI} = [];
                    sceneSet = SceneSets(ssI);
                    
                    for pose = Poses
                        
                        %%
                        % Get the data for this pose, sceneset,
                        % textureConditio and nr-of-objects.
                        dataS = dataTotal(...
                            dataTotal(:,h{fileI}.textureConditionID)==textureConditionID & ...
                            dataTotal(:,h{fileI}.nrObjects)==singleDoubleI & ...
                            dataTotal(:,h{fileI}.sceneSetID)==sceneSet & ...
                            dataTotal(:,h{fileI}.poseID)==pose, ...
                            :);
                        dataSuccess = dataS(dataS(:,h{fileI}.graspResult)==resSuccess, :);
                        dataObjectSlipped = dataS(dataS(:,h{fileI}.graspResult)==resObjectSlipped, :);
                        dataObjectDropped = dataS(dataS(:,h{fileI}.graspResult)==resObjectDropped, :);
                        dataObjectMissed = dataS(dataS(:,h{fileI}.graspResult)==resObjectMissed, :);
                        dataCollisionInitially = dataS(dataS(:,h{fileI}.graspResult)==resCollisionInitially, :);
                        dataUnInitialized = dataS(dataS(:,h{fileI}.graspResult)==resUnInitialized, :);
                        dataTimeOut = dataS(dataS(:,h{fileI}.graspResult)==resTimeOut, :);
                        dataSimulationFailure = dataS(dataS(:,h{fileI}.graspResult)==resSimulationFailure, :);
                        

                        nrSuccess = size(dataSuccess, 1);
                        nrObjectSlipped = size(dataObjectSlipped, 1);
                        nrObjectDropped = size(dataObjectDropped, 1);
                        nrObjectMissed = size(dataObjectMissed, 1);
                        nrCollisionInitially = size(dataCollisionInitially,1);
                        nrUnInitialized = size(dataUnInitialized, 1);
                        nrTimeOut = size(dataTimeOut, 1);
                        nrSimulationFailure = size(dataSimulationFailure, 1);
                        nrTotal = size(dataS, 1);
                        
                        % Get the two quality measures (lift quality, and wrench
                        % space) for successful grasp (=success or
                        % slipped).
                        liftQuality = [ ...
                            dataSuccess(:,h{fileI}.liftQuality); ...
                            dataObjectSlipped(:,h{fileI}.liftQuality); ...
                            ];
                        if(~isempty(liftQuality))
                            averageLiftQuality = mean(liftQuality);
                        else
                            averageLiftQuality = 0;
                        end
                        wrenchSpace = [ ...
                            dataSuccess(:,h{fileI}.liftGWSQuality); ...
                            dataObjectSlipped(:,h{fileI}.liftGWSQuality); ...
                            ];
                        if(~isempty(wrenchSpace))
                            averageWrenchSpace = mean(abs(wrenchSpace));
                        else
                            averageWrenchSpace = 0;
                        end
                        % Gather the averages for this scene and store them
                        % in Results and ResultsPerObject
                        if(size(dataS,1) > 0)
                            results = [nrSuccess/nrTotal ...
                                nrObjectSlipped/nrTotal ...
                                nrObjectDropped/nrTotal ...
                                nrObjectMissed/nrTotal ...
                                nrCollisionInitially/nrTotal ...
                                0 ...
                                (nrUnInitialized+nrTimeOut+nrSimulationFailure)/nrTotal ...
                                averageLiftQuality ...
                                averageWrenchSpace];
                        else % There are no grasps selected, mark this as object missed
                            results = [0 0 0 0 0 1 0 0.0 0.0];
                        end
                        Results{fileI} = [Results{fileI}; results];
                        ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{fileI} = ...
                            [ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{fileI}; results];
                        
                    end % for pose = Poses
                end % ssI = 1:length(SceneSets)
            end % fileI = 1:length(ResultDataFiles)

            %%
            % Write the results to the file
            if(strcmp(outputType, 'tex'))
                writeTEXContentAllObjectDist(fdResDist, sceneSectionDescription, singleDoubleI, sceneSectionI, ...
                    MethodLabels, Results, resultType);
                writeTEXContentAllObjectMeas(fdResMeas, sceneSectionDescription, singleDoubleI, sceneSectionI, ...
                    MethodLabels, Results, resultType);
            elseif(strcmp(outputType, 'html'))
                writeHTMLContentAllObjectDist(fdResDist, sceneSectionDescription, singleDoubleI, sceneSectionI, ...
                    MethodLabels, Results, resultType);
                writeHTMLContentAllObjectMeas(fdResMeas, sceneSectionDescription, singleDoubleI, sceneSectionI, ...
                    MethodLabels, Results, resultType);
            else
                plotContentAllObject(textureCondition, complexity, sceneSectionDescription, singleDoubleI, sceneSectionI, ...
                    MethodLabels, Results, resultType);
            end            
            %%
        end % for SceneSectionI=1:3
        %%
        if(strcmp(outputType, 'tex'))
            writeTEXEndAllObjectTabularDist(fdResDist);
            writeTEXEndAllObjectTabularMeas(fdResMeas, singleDoubleI);
        elseif(strcmp(outputType, 'html'))
            writeHTMLEndAllObjectTabularDist(fdResDist);
            writeHTMLEndAllObjectTabularMeas(fdResMeas, singleDoubleI);
        else
            
            figName = sprintf('plot_%s_%s.pdf', textureCondition, complexity);
            export_fig(figName, '-pdf');
        end
        
    end % singleDoubleI=1:2
    
    if(strcmp(outputType, 'tex'))
        writeTEXEndAllObjectTableDist(fdResDist);
        writeTEXEndAllObjectTableMeas(fdResMeas);
    elseif(strcmp(outputType, 'html'))
        writeHTMLEndAllObjectTableDist(fdResDist);
        writeHTMLEndAllObjectTableMeas(fdResMeas);
    end
    
    %%
    % Write the results per object
    if(strcmp(outputType, 'tex'))
        writeTEXTablePerObject(SceneSetsSD, MethodLabels, ResultsPerObject, ...
            doubleObjectCombination, textureCondition);
    elseif(strcmp(outputType, 'html'))
        writeHTMLTablePerObject(SceneSetsSD, MethodLabels, ResultsPerObject, ...
            doubleObjectCombination, textureCondition);
    end

end
end

function writeTEXBeginAllObjectTableDist(fdRes, condition)
fprintf(fdRes, '\\begin{table}\n');
fprintf(fdRes, '\\caption{Results for the %s scenes. The percentages are\n', condition);
fprintf(fdRes, 'the average over the different objects and poses. The values in bold\n');
fprintf(fdRes, 'font are, respectively, the average lift quality and the average\n');
fprintf(fdRes, 'grasp wrench-space quality of the successful trials (stable, slipped).}\n\n');
end

function writeTEXBeginAllObjectTableMeas(fdRes, condition )
fprintf(fdRes, '\\begin{table}\n');
fprintf(fdRes, '\\caption{The lift quality and grasp wrench-space quality for the %s scenes.\n', condition);
fprintf(fdRes, 'The values are the averages over the successful trials (stable, slipped).}\n\n');

end

%%
% Write the TEX header for the all-object table
function writeTEXHeaderAllObjectDist(fdRes, singleDoubleI, MethodLabels)

if(singleDoubleI==1)
    fprintf(fdRes,'\\vspace{0.2cm}\n{\\bf Single-object scenes}\n\n');
else
    fprintf(fdRes,'\\vspace{0.2cm}\n{\\bf Double-object scenes}\n\n');
end
fprintf(fdRes,'\\begin{tabular}{|l |');
for methI = 1:length(MethodLabels)
    fprintf(fdRes,' c');
end
fprintf(fdRes,'|}\n');
fprintf(fdRes,'\\hline\n');
fprintf(fdRes,' ');
for methI = 1:length(MethodLabels)
    fprintf(fdRes,' & $%s$', MethodLabels{methI});
end
fprintf(fdRes,' \\\\ \n');
end
%%

%%
% Write the TEX header for the all-object table
function writeTEXHeaderAllObjectMeas(fdRes, singleDoubleI, MethodLabels)

if(singleDoubleI==1)
    fprintf(fdRes,'\\begin{tabular}{| l | r |');
    for methI = 1:length(MethodLabels)
        fprintf(fdRes,' c c |');
    end
    fprintf(fdRes,'}\n');
    fprintf(fdRes,'\\hline\n');
    fprintf(fdRes,' \\multicolumn{2}{|c|}{}');
    for methI = 1:length(MethodLabels)
        fprintf(fdRes,' & \\multicolumn{2}{c|}{$%s$}', MethodLabels{methI});
    end
    fprintf(fdRes,' \\\\ \n');
    
    fprintf(fdRes,' \\multicolumn{2}{|c|}{}');
    for methI = 1:length(MethodLabels)
        fprintf(fdRes,' & $Q_l$ & $Q_{\\mathrm{GWS}}$');
    end
    fprintf(fdRes,' \\\\ \n');
end
fprintf(fdRes,'\\hline\n');

if(singleDoubleI==1)
    fprintf(fdRes,'\\multirow{%d}{*}{\\begin{sideways}Single\\end{sideways}} ', 3);
else
    fprintf(fdRes,'\\multirow{%d}{*}{\\begin{sideways}Double\\end{sideways}} ', 3);
end

end
%%

%%
% Write the TEX content for the all-object table
function writeTEXContentAllObjectDist(fdRes, sceneSectionDescription, singleDoubleI, sceneSectionI, MethodLabels, Results, resultType)

fprintf(fdRes,'\\hline\n');
% Print condition (standing/laying/all, far/close/all)
fprintf(fdRes,'{\\bf %s}:', sceneSectionDescription{singleDoubleI}{sceneSectionI});
% Print average lift quality and wrench-space (for successful grasps)
for methI = 1:length(MethodLabels)
    %averageLiftQuality = mean(Results{methI}(:,end-1));
    %averageWrenchSpace = mean(Results{methI}(:,end));
    %fprintf(fdRes,' & {\\bf \\em %1.2f , %1.2f}', averageLiftQuality, averageWrenchSpace);
    fprintf(fdRes,' & ');
end
fprintf(fdRes,'\\\\ \n');
for resTypeI = 1:length(resultType)  % Loop over all grasp outcomes (success, slipped, etc.)
    if(resTypeI<=2)
        fprintf(fdRes,'\\hspace{0.1cm} \\emph{%s}', resultType{resTypeI});
    else
        fprintf(fdRes,'\\hspace{0.1cm} %s', resultType{resTypeI});
    end
    for methI = 1:length(MethodLabels)
        % Get mean and std error of the results for this
        % (sub)method
        meanResults{methI} = mean(Results{methI}, 1);
        stdeResults{methI} = std(Results{methI}, [], 1) / sqrt( size(Results{methI},1) );
        %fprintf(fdRes,' & %1.2f (%1.2f)', meanResults{subGraspI}(resTypeI), stdeResults{subGraspI}(resTypeI));
        if(resTypeI<=2)
            fprintf(fdRes,' & \\emph{%d \\%%} ', round(100*meanResults{methI}(resTypeI)));
        else
            fprintf(fdRes,' & %d \\%% ', round(100*meanResults{methI}(resTypeI)));
        end
        %subGraspI = subGraspI+1;
    end
    fprintf(fdRes,'\\\\\n');
end
end
%%

%%
% Write the TEX content for the all-object table
function writeTEXContentAllObjectMeas(fdRes, sceneSectionDescription, singleDoubleI, sceneSectionI, MethodLabels, Results, resultType)

%fprintf(fdRes,'\\hline\n');
% Print condition (standing/laying/all, far/close/all)
if(sceneSectionI>0)
    fprintf(fdRes, ' &');
end
fprintf(fdRes,'%s', sceneSectionDescription{singleDoubleI}{sceneSectionI});
    
% Print average lift quality and wrench-space (for successful grasps)
for methI = 1:length(MethodLabels)
    averageLiftQuality = mean(Results{methI}(:,end-1));
    averageWrenchSpace = mean(Results{methI}(:,end));
    fprintf(fdRes,' & %1.2f & %1.2f', averageLiftQuality, averageWrenchSpace);
end
fprintf(fdRes,'\\\\ \n');
end
%%

function writeTEXEndAllObjectTabularDist(fdRes)
fprintf(fdRes,'\\hline\n');
fprintf(fdRes,'\\end{tabular}\n\n');
end

function writeTEXEndAllObjectTabularMeas(fdRes, singleDoubleI)
if(singleDoubleI==2)
    fprintf(fdRes,'\\hline\n');
    fprintf(fdRes,'\\end{tabular}\n\n');
end
end

function writeTEXEndAllObjectTableDist(fdRes)
fprintf(fdRes,'\\end{table}\n');
end

function writeTEXEndAllObjectTableMeas(fdRes)
%fprintf(fdRes,'\\hline\n');
%fprintf(fdRes,'\\end{tabular}\n\n');

fprintf(fdRes,'\\end{table}\n');
end

%%
% Write the TEX tables per object
function writeTEXTablePerObject(SceneSetsSD, MethodLabels, ResultsPerObject, doubleObjectCombination, condition);

fdObj = fopen( sprintf('results_objects_%s.tex', condition), 'w+' );

fprintf(fdObj,'\n\n');
fprintf(fdObj,'\\begin{table}\n');
for singleDoubleI=1:2
    SceneSets = SceneSetsSD{singleDoubleI} ;
    
    if(singleDoubleI==1)
        fprintf(fdObj,'\\vspace{0.2cm}\n{\\bf Single-object scenes}\n\n');
    else
        fprintf(fdObj,'\\vspace{0.2cm}\n{\\bf Double-object scenes}\n\n');
    end
    fprintf(fdObj,'\\begin{tabular}{|l |');
    for methI = 1:length(MethodLabels)
        fprintf(fdObj,'cc|');
    end
    fprintf(fdObj,'}\n');
    fprintf(fdObj,'\\hline\n');
    fprintf(fdObj,' ');
    for methI = 1:length(MethodLabels)
        fprintf(fdObj,' & \\multicolumn{2}{c|}{$%s$}', MethodLabels{methI});
    end
    fprintf(fdObj,' \\\\ \n');

    fprintf(fdObj,' ');
    for methI = 1:length(MethodLabels)
        if(singleDoubleI==1)
            fprintf(fdObj,' & s & l');
        else
            fprintf(fdObj,' & f & c');
        end
    end
    fprintf(fdObj,' \\\\ \n');
    fprintf(fdObj,'\\hline\n');

    for ssI = 1:length(SceneSets)
        if singleDoubleI==1
            fprintf(fdObj,'%d', ssI);
        else
            fprintf(fdObj,'%c', 96+ssI);
        end
        %         if singleDoubleI==1
        %             fprintf(fdObj,'%s ',singleObject{ssI});
        %         else
        %             fprintf(fdObj,'%s ',doubleObject{ssI});
        %         end
        for methI = 1:length(MethodLabels)
            for sceneSectionI=1:2 % All is not shown
                % Get the percentage of successful grasps (=successful
                % or slipped)
                if(size( ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{methI}, 1) > 0)
                    meanResultsPerObject = mean( ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{methI} ,1);
                    successP = meanResultsPerObject(1) + meanResultsPerObject(2); % Stable and Slipped
                    fprintf(fdObj,' &%d \\%%', round(100*successP));
                else
                    fprintf(fdObj,' &-');
                end
            end
        end
        fprintf(fdObj,'\\\\\n');
    end
    fprintf(fdObj,'\\hline\n');
    fprintf(fdObj,'\\end{tabular}\n\n');
    
    if singleDoubleI==2
        fprintf(fdObj,'\\caption{Percentage of successful grasps for the different objects in\n');
        fprintf(fdObj,'the %s scenes. Results for the single-object scenes are split\n', condition);
        fprintf(fdObj,'into standing (s) and laying (l) object poses and for the\n');
        fprintf(fdObj,'double-object scenes into far (f) and close (c).\n');
        fprintf(fdObj,'The pairs in the double-object scenes are: \n');
        for ssI = 1:length(SceneSets)
            if ssI==1
                fprintf(fdObj,'%c: %s', 96+ssI, doubleObjectCombination{ssI});
            else
                fprintf(fdObj,', %c: %s', 96+ssI, doubleObjectCombination{ssI});
            end
        end
        fprintf(fdObj,'.}\n\n');
    end
end
fprintf(fdObj,'\\end{table}');
fclose(fdObj);
end

function writeHTMLBeginAllObjectTableDist(fdRes, condition)
fprintf(fdRes, 'Results for the %s scenes. The percentages are\n', condition);
fprintf(fdRes, 'the average over the different objects and poses.  The values in bold\n');
fprintf(fdRes, 'font are, respectively, the average lift quality and the average');
fprintf(fdRes, 'grasp wrench-space quality of the successful trials (stable, slipped).<p>\n');
end

function writeHTMLBeginAllObjectTableMeas(fdRes, condition)
fprintf(fdRes, 'The lift quality and grasp wrench-space quality for the %s scenes.\n', condition);
fprintf(fdRes, 'The values are the averages over the successful trials (stable, slipped).<p>\n');
end

%%
% Write the HTML header for the all-object table
function writeHTMLHeaderAllObjectDist(fdRes, singleDoubleI, MethodLabels)

if(singleDoubleI==1)
    fprintf(fdRes,'<b>Single-object scenes</b><p>\n');
else
    fprintf(fdRes,'<b>Double-object scenes</b><p>\n');
end
fprintf(fdRes,'<table>\n');
fprintf(fdRes,'<tr>\n');
fprintf(fdRes,'<th>&nbsp;</th>\n');
for methI = 1:length(MethodLabels)
    fprintf(fdRes,'<th align=center>%s</th>\n', MethodLabels{methI});
end
fprintf(fdRes,'</tr>\n');
end
%%


%%
% Write the HTML header for the all-object table
function writeHTMLHeaderAllObjectMeas(fdRes, singleDoubleI, MethodLabels)

if(singleDoubleI==1)
    fprintf(fdRes,'<table>\n');
    fprintf(fdRes,'<tr>\n');
    fprintf(fdRes,'<th colspan=2>&nbsp;</th>\n');
    for methI = 1:length(MethodLabels)
        fprintf(fdRes,'<th align=center colspan=2>%s</th>\n', MethodLabels{methI});
    end
    fprintf(fdRes,'</tr>\n');

    fprintf(fdRes,'<tr>\n');
    fprintf(fdRes,'<th>&nbsp;</th>\n');
    fprintf(fdRes,'<th>&nbsp;</th>\n');
    for methI = 1:length(MethodLabels)
        fprintf(fdRes,'<th align=center>Q_l</th><th align=center>Q_GWS</th>\n');
    end
    fprintf(fdRes,'</tr>\n');
end
if(singleDoubleI==1)
    fprintf(fdRes, '<tr><td rowspan=3><div style=\"font-weight:bold; -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); display: block; writing-mode: tb-rl;\">Single</div></td>');
else
    fprintf(fdRes, '<tr><td rowspan=3><div style=\"font-weight:bold;  -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); display: block; writing-mode: tb-rl;\">Double</div></td>');
end

end
%%

%%
% Write the HTML content for the all-object table
function writeHTMLContentAllObjectDist(fdRes, sceneSectionDescription, singleDoubleI, sceneSectionI, MethodLabels, Results, resultType)

fprintf(fdRes,'<tr>\n');
% Print condition (standing/laying/all, far/close/all)
fprintf(fdRes,'<td><b>%s</b>:</td>\n', sceneSectionDescription{singleDoubleI}{sceneSectionI});
% Print average lift quality and wrench-space (for successful grasps)
for methI = 1:length(MethodLabels)
    %averageLiftQuality = mean(Results{methI}(:,end-1));
    %averageWrenchSpace = mean(Results{methI}(:,end));
    %fprintf(fdRes,'<td align=center><b><em>%1.2f , %1.2f</em></b></td>\n', averageLiftQuality, averageWrenchSpace);
    fprintf(fdRes,'<td align=center>&nbsp;</td>\n');
end
fprintf(fdRes,'</tr>\n');
for resTypeI = 1:length(resultType)  % Loop over all grasp outcomes (success, slipped, etc.)
    fprintf(fdRes, '<tr>\n');
    if(resTypeI<=2)
        fprintf(fdRes,'<td>&nbsp;<em>%s</em></td>\n', resultType{resTypeI});
    else
        fprintf(fdRes,'<td>&nbsp;%s</td>\n', resultType{resTypeI});
    end
    for methI = 1:length(MethodLabels)
        % Get mean and std error of the results for this
        % (sub)method
        meanResults{methI} = mean(Results{methI}, 1);
        stdeResults{methI} = std(Results{methI}, [], 1) / sqrt( size(Results{methI},1) );
        %fprintf(fdRes,' & %1.2f (%1.2f)', meanResults{subGraspI}(resTypeI), stdeResults{subGraspI}(resTypeI));
        if(resTypeI<=2)
            fprintf(fdRes,'<td align=center><em>%d %%</em></td>\n', round(100*meanResults{methI}(resTypeI)));
        else
            fprintf(fdRes,'<td align=center>%d %%</td>\n', round(100*meanResults{methI}(resTypeI)));
        end
        %subGraspI = subGraspI+1;
    end
    fprintf(fdRes,'</tr>\n');
end
end
%%

%%
% Write the HTML content for the all-object table
function writeHTMLContentAllObjectMeas(fdRes, sceneSectionDescription, singleDoubleI, sceneSectionI, MethodLabels, Results, resultType)

%fprintf(fdRes,'<tr>\n');
% Print condition (standing/laying/all, far/close/all)
fprintf(fdRes,'<td>%s</td>\n', sceneSectionDescription{singleDoubleI}{sceneSectionI});
% Print average lift quality and wrench-space (for successful grasps)
for methI = 1:length(MethodLabels)
    averageLiftQuality = mean(Results{methI}(:,end-1));
    averageWrenchSpace = mean(Results{methI}(:,end));
    fprintf(fdRes,'<td align=center>%1.2f</td> <td align=center>%1.2f</td>\n', averageLiftQuality, averageWrenchSpace);
end
fprintf(fdRes,'</tr>\n');
end
%%

%%
% Write the TEX tables per object
function writeHTMLTablePerObject(SceneSetsSD, MethodLabels, ResultsPerObject, doubleObjectCombination, condition)

fdObj = fopen( sprintf('results_objects_%s.html', condition), 'w+' );

for singleDoubleI=1:2
    SceneSets = SceneSetsSD{singleDoubleI} ;
    
    if singleDoubleI==1
        fprintf(fdObj,'Percentage of successful grasps for the different objects in\n');
        fprintf(fdObj,'the %s scenes. Results for the single-object scenes are split\n', condition);
        fprintf(fdObj,'into standing (s) and laying (l) object poses and for the\n');
        fprintf(fdObj,'double-object scenes into far (f) and close (c).<p>\n');
    end
    
    if(singleDoubleI==1)
        fprintf(fdObj,'<b>Single-object scenes</b>\n');
    else
        fprintf(fdObj,'<b>Double-object scenes</b>\n');
    end
    if singleDoubleI==2
        fprintf(fdObj,'The pairs in the double-object scenes are: \n');
        for ssI = 1:length(SceneSets)
            if ssI==1
                fprintf(fdObj,'%c: %s', 96+ssI, doubleObjectCombination{ssI});
            else
                fprintf(fdObj,', %c: %s', 96+ssI, doubleObjectCombination{ssI});
            end
        end
        fprintf(fdObj,'<p>\n');
    end
    fprintf(fdObj,'<table>\n');
    fprintf(fdObj,'<tr>\n');
    fprintf(fdObj,'<th>&nbsp;</th>\n');
    for methI = 1:length(MethodLabels)
        fprintf(fdObj,'<th colspan=2 align=center>%s</th>\n', MethodLabels{methI});
    end
    fprintf(fdObj,'</tr>\n');

    fprintf(fdObj,'<tr>\n');
    fprintf(fdObj,'<th>&nbsp;</th>\n');
    for methI = 1:length(MethodLabels)
        if(singleDoubleI==1)
            fprintf(fdObj,'<th align=center>s</th><th align=center>l</th>\n');
        else
            fprintf(fdObj,'<th align=center>f</th><th align=center>c</th>\n');
        end
    end
    fprintf(fdObj,'</tr>\n');

    for ssI = 1:length(SceneSets)
        fprintf(fdObj,'<tr>\n');
        if singleDoubleI==1
            fprintf(fdObj,'<td>%d</td>\n', ssI);
        else
            fprintf(fdObj,'<td>%c</td>\n', 96+ssI);
        end
        %         if singleDoubleI==1
        %             fprintf(fdObj,'%s ',singleObject{ssI});
        %         else
        %             fprintf(fdObj,'%s ',doubleObject{ssI});
        %         end
 
        for methI = 1:length(MethodLabels)
            for sceneSectionI=1:2 % All is not shown
                % Get the percentage of successful grasps (=successful
                % or slipped)
                if(size( ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{methI}, 1) > 0)
                    meanResultsPerObject = mean( ResultsPerObject{singleDoubleI}{sceneSectionI}{ssI}{methI} ,1);
                    successP = meanResultsPerObject(1) + meanResultsPerObject(2); % Stable and Slipped
                    fprintf(fdObj,'<td align=center>%d %%</td>\n', round(100*successP));
                else
                    fprintf(fdObj,'<td align=center>-</td>\n');
                end
            end
        end
        fprintf(fdObj,'</tr>\n');
    end
    fprintf(fdObj,'</table><p>\n');
    
end
fprintf(fdObj,'<p>\n');
fclose(fdObj);
end

function writeHTMLEndAllObjectTabularDist(fdRes)
fprintf(fdRes,'</table>\n');
fprintf(fdRes,'<p>\n');
end

function writeHTMLEndAllObjectTabularMeas(fdRes, singleDoubleI)
if(singleDoubleI==2) 
    fprintf(fdRes,'</table>\n');
    fprintf(fdRes,'<p>\n');
end
end

function writeHTMLEndAllObjectTableDist(fdRes)

end

function writeHTMLEndAllObjectTableMeas(fdRes)

end

%%
%
function createPlot() 
global plotWidth
global plotHeight;
figure('Color', 'white', 'Position', [10,10, plotWidth, plotHeight]);
end
%

%%
% Make the plot for the all-object table
function plotContentAllObject(condition, complexity, sceneSectionDescription, singleDoubleI, sceneSectionI, ...
    MethodLabels, Results, resultType)

subplot(1, 3, sceneSectionI, 'Position', [(sceneSectionI-1)*0.33+0.05 0.35 0.28 0.45]);

% Print average lift quality and wrench-space (for successful grasps)
for methI = 1:length(MethodLabels)
    averageLiftQuality = mean(Results{methI}(:,end-1));
    averageWrenchSpace = mean(Results{methI}(:,end));
    %fprintf(fdRes,' & {\\bf \\em %1.2f , %1.2f}', averageLiftQuality, averageWrenchSpace);
end

BarData = zeros(length(MethodLabels), length(resultType));
for methI = 1:length(MethodLabels)
    % Get mean and std error of the results for this
    % (sub)method
    meanResults{methI} = mean(Results{methI}, 1);
    stdeResults{methI} = std(Results{methI}, [], 1) / sqrt( size(Results{methI},1) );

    for resTypeI = 1:length(resultType)  % Loop over all grasp outcomes (success, slipped, etc.)
        BarData(methI,resTypeI) = meanResults{methI}(resTypeI);
    end
end

if(size(BarData,1)==1)
    bar([BarData;nan(size(BarData))],'stacked'); xlim([.5,1.5]);
else
    bar(BarData, 'stacked');
end

title(sceneSectionDescription{singleDoubleI}{sceneSectionI}, 'FontSize', 10);
if(sceneSectionI==3)
    h1 = legend(gca, resultType, 'Orientation','horizontal');
    p = get(h1,'Position');
    p(1) = (1-p(3))/2; 
    p(2) = 0;
    set(h1,'Position',p);
end
set(gca,'XTickLabel',MethodLabels);
rotateticklabel(gca, -45, 8);
C = [0 0.5 0; 0.5 1 0; 1 1 0; 1 0.6 0; 0.9 0 0; 0.7 0.7 0.7];
colormap(C);
set(gca, 'Box', 'off');

if(sceneSectionI==3)
    t = sprintf('%s background, %s-object scenes', condition, complexity);
    t = regexprep(t,'(\<[a-z])','${upper($1)}');
    [ax,h2] = suplabel(t, 't');
    set(h2, 'FontSize', 11);
    p2 = get(h2, 'Position');
    p2(2) = 1.15;
    set(h2, 'Position', p2);
end

end
%%



